<template>
  <div class="register-container">
    <h2>用户注册</h2>
    <el-form :model="form" @submit.prevent="handleRegister" :rules="rules">
      <el-form-item>
        <el-input v-model="form.username" placeholder="用户名" />
      </el-form-item>
      <el-form-item>
        <el-input v-model="form.password" type="password" placeholder="密码" />
      </el-form-item>
      <el-form-item>
        <el-input v-model="form.email" placeholder="邮箱" />
      </el-form-item>
      <el-button type="primary" native-type="submit" :loading="loading">
        注册
      </el-button>
      <el-button @click="router.push('/login')">已有账号？去登录</el-button>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { ElMessage } from 'element-plus'

const router = useRouter()
const authStore = useAuthStore()
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 16, message: '长度在3到16个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在6到20个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ]
}

const form = ref({
  username: '',
  password: '',
  email: ''
})
const loading = ref(false)

const handleRegister = async () => {
  try {
    loading.value = true
    await authStore.register(form.value)
    ElMessage.success('注册成功！')
    router.push('/login')
  } catch (error) {
    ElMessage.error('注册失败: ' + (error as Error).message)
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.register-container {
  max-width: 400px;
  margin: 100px auto;
  padding: 20px;
  border: 1px solid #eee;
  border-radius: 4px;
}
</style>